import os
import sys
import time
import logging
from typing import List
import winerror
import traceback
import win32event
import win32service
import win32timezone
import servicemanager
import win32serviceutil
from win32service import OpenSCManager
from win32service import OpenService
from win32service import QueryServiceStatus
from workers01.WS0201 import WorkWS0201
from workers01.WS0202 import WorkWS0202
from workers01.WS0203 import WorkWS0203
from workers01.WS0204 import WorkWS0204
from workers01.WS0205 import WorkWS0205
from workers01.WS0206 import WorkWS0206
from workers01.WS0207 import WorkWS0207
from workers01.WS0208 import WorkWS0208
from workers01.WS0209 import WorkWS0209



logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s: %(message)s")
services: List[dict] = [
    {
        "routine": None,
        "model": "WorkWS0201()"
    },
    {
        "routine": None,
        "model": "WorkWS0202()"
    },
    {
        "routine": None,
        "model": "WorkWS0203()"
    },
    {
        "routine": None,
        "model": "WorkWS0204()"
    },
    {
        "routine": None,
        "model": "WorkWS0205()"
    },
    {
        "routine": None,
        "model": "WorkWS0206()"
    },
    {
        "routine": None,
        "model": "WorkWS0207()"
    },
    {
        "routine": None,
        "model": "WorkWS0208()"
    },
    {
        "routine": None,
        "model": "WorkWS0209()"
    }
]

class AppKZLServicesViSu01A(win32serviceutil.ServiceFramework):
    # 注册服务名
    _svc_name_ = "AppKZLServicesViSu01A"
    # 服务在windows系统中显示的名称
    _svc_display_name_ = "AppKZLServicesViSu01A"
    # 服务描述
    _svc_description_ = "AppKZLServicesViSu01A"

    def __init__(self, args):
        win32serviceutil.ServiceFramework.__init__(self, args)
        self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
        self.status: bool = True

    def SvcDoRun(self):
        time.sleep(2.8)
        # noinspection PyBroadException
        try:
            while True:
                for f_index, f_itr in enumerate(services):
                    if f_itr.get("routine") is None or f_itr.get("routine").is_alive() is False:
                        f_itr["routine"] = eval(f_itr.get("model"))
                        f_itr["routine"].start()
                time.sleep(2.8)
        except Exception as e:
            logging.error(msg=traceback.print_exc())

    def SvcStop(self):
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        win32event.SetEvent(self.hWaitStop)
        self.ReportServiceStatus(win32service.SERVICE_STOPPED)
        self.status = False


if __name__ == '__main__':
    if len(sys.argv) == 1:
        try:
            servicemanager.Initialize()
            servicemanager.PrepareToHostSingle(AppKZLServicesViSu01A)
            servicemanager.StartServiceCtrlDispatcher()
        except Exception as details:
            if details == winerror.ERROR_FAILED_SERVICE_CONTROLLER_CONNECT:
                win32serviceutil.usage()
    else:
        win32serviceutil.HandleCommandLine(AppKZLServicesViSu01A)

    # noinspection PyBroadException
    try:
        while True:
            for f_index0, f_itr0 in enumerate(services):
                if f_itr0.get("routine") is None or f_itr0.get("routine").is_alive() is False:
                    f_itr0["routine"] = eval(f_itr0.get("model"))
                    f_itr0["routine"].start()
            time.sleep(2.8)
    except Exception as e:
        logging.error(msg=traceback.print_exc())
